<?php
error_reporting(E_ERROR | E_PARSE);
//test_house script script created by Robert Cox on August 15, 2011
//Commandline Usage: ./beta_mimetype.php commandline
//URL Usage: http://tests.aimatch.com/tests/beta_mimetype.php?web=1      <= normal mode
//      -or- http://tests.aimatch.com/tests/beta_mimetype.php?web=1      <= debug mode

// set start time
$mtime = microtime();
$mtime = explode(' ', $mtime);
$mtime = $mtime[1] + $mtime[0];
$starttime = $mtime;

if(isset($_GET['debug'])){
                $debug = TRUE;
                $GLOBALS["debug"] = TRUE;
        } else {
                unset($debug);
        }

if(isset($_GET['web'])){
                $web = TRUE;
                $GLOBALS["web"] = TRUE;
        } else {
                unset($web);
        }


if (isset($debug)) { 
	echo "<br>* * * * *  D E B U G = O N * * * * *<br>";
	if (isset($web)) { 
		echo "<br>* * * * *  W E B = O N  * * * * *<br>";}
}

$status = "pending";
$testname = "Mime Type Test";
$testshortname = "mimetypetest";
$testdesc = "Verify that custom mime types are working";
$testurl = "test_mimetype.php";
$testtime = time();


$today = date("F j, Y, g:i a");
$hour = date("G");
$datestamp = date("Y-m-d");
$random = rand();
$Targeting="\"house\"";


// setup command line args (commandline only)
if (isset($argv[1])) { $commandline = $argv[1]; unset($debug);} 

$i=0;

//
// Test 1: Verify that requests to an ad with a custom mime type is successful
// http://crtldev.aimatch.com:60000/canary/hserver/site=canary/area=contenttype/mimetype=canary/mid=1111
//
	$web_output = $web_output."<font face=\"Tahoma\" size=\"3\"><b>Test 1: Verify that requests to an ad with a custom mime type are successful</b><br></font><br>"; 
	$commandline_output = $commandline_output."Test 1: Verify that requests to an ad with a custom mime type are successful\n\n"; 

    $url = "http://crtldev.aimatch.com:60000/canary/hserver/mid=".$testtime."1/site=canary/area=contenttype/mimetype=canary/trace=3";
	$output = MakeAdCall($url);
	$output_array = MakeOutputArray($output);
	$formatted_output = GetFormattedOutput($output_array,$web,$debug);
	$text1 = "The correct ad was returned for the ad call that was made";
	$text2 = "";
	$text3 = "The response to the ad call returned:";
	list($status1,$web_message1,$web_message2,$web_message3,$cl_message1,$cl_message2,$cl_message3) = CheckResponse($text1,$text2,$text3,$output,"canary/tweety",$web);
	$web_output = $web_output.$web_message1.$web_message2.$web_message3."<hr>"; 
	$commandline_output = $commandline_output.$cl_message1.$cl_message2.$cl_message3."\n"; 

//
// Test 2: Verify that requests to an ad with an HSERVER call return text/html Content-Type
// http://crtldev.aimatch.com:60000/canary/hserver/site=canary/area=contenttype/mimetype=html/mid=1111
//
	$web_output = $web_output."<font face=\"Tahoma\" size=\"3\"><b>Test 2: Verify that requests to an ad with an HSERVER call return text/html Content-Type</b><br></font><br>"; 
	$commandline_output = $commandline_output."Test 2: Verify that requests to an ad with an HSERVER call return text/html Content-Type\n\n"; 

    $url = "http://crtldev.aimatch.com:60000/canary/hserver/mid=".$testtime."2/site=canary/area=contenttype/mimetype=html/trace=3";
	$output = MakeAdCall($url);
	$output_array = MakeOutputArray($output);
	$formatted_output = GetFormattedOutput($output_array,$web,$debug);
	$text1 = "The correct ad was returned for the ad call that was made";
	$text2 = "";
	$text3 = "The response to the ad call returned:";
	list($status2,$web_message1,$web_message2,$web_message3,$cl_message1,$cl_message2,$cl_message3) = CheckResponse($text1,$text2,$text3,$output,"text/html",$web);
	$web_output = $web_output.$web_message1.$web_message2.$web_message3."<hr>"; 
	$commandline_output = $commandline_output.$cl_message1.$cl_message2.$cl_message3."\n"; 

//
// Test 3: Verify that requests to an ad with an JSERVER call return application/javascript Content-Type
// http://crtldev.aimatch.com:60000/canary/jserver/site=canary/area=contenttype/mimetype=html/mid=1111
//
	$web_output = $web_output."<font face=\"Tahoma\" size=\"3\"><b>Test 3: Verify that requests to an ad with an JSERVER call return application/javascript Content-Type</b><br></font><br>"; 
	$commandline_output = $commandline_output."Test 3: Verify that requests to an ad with an JSERVER call return application/javascript Content-Type\n\n"; 

    $url = "http://crtldev.aimatch.com:60000/canary/jserver/mid=".$testtime."3/site=canary/area=contenttype/mimetype=javascript/trace=3";
	$output = MakeAdCall($url);
	$output_array = MakeOutputArray($output);
	$formatted_output = GetFormattedOutput($output_array,$web,$debug);
	$text1 = "The correct ad was returned for the ad call that was made";
	$text2 = "";
	$text3 = "The response to the ad call returned:";
	list($status3,$web_message1,$web_message2,$web_message3,$cl_message1,$cl_message2,$cl_message3) = CheckResponse($text1,$text2,$text3,$output,"application/x-javascript",$web);
	$web_output = $web_output.$web_message1.$web_message2.$web_message3."<hr>"; 
	$commandline_output = $commandline_output.$cl_message1.$cl_message2.$cl_message3."\n"; 

//
// Test 4: Verify that requests to an ad with a custom mime type using a JSERVER call will still return application/javascript Content-Type
// http://crtldev.aimatch.com:60000/canary/jserver/site=canary/area=contenttype/mimetype=html/mid=1111
//
	$web_output = $web_output."<font face=\"Tahoma\" size=\"3\"><b>Test 4: Verify that requests to an ad with a custom mime type using a JSERVER call will still return application/javascript Content-Type</b><br></font><br>"; 
	$commandline_output = $commandline_output."Test 4: Verify that requests to an ad with a custom mime type using a JSERVER call will still return application/javascript Content-Type\n\n"; 

    $url = "http://crtldev.aimatch.com:60000/canary/jserver/mid=".$testtime."4/site=canary/area=contenttype/mimetype=canary/trace=3";
	$output = MakeAdCall($url);
	$output_array = MakeOutputArray($output);
	$formatted_output = GetFormattedOutput($output_array,$web,$debug);
	$text1 = "The correct ad was returned for the ad call that was made";
	$text2 = "";
	$text3 = "The response to the ad call returned:";
	list($status4,$web_message1,$web_message2,$web_message3,$cl_message1,$cl_message2,$cl_message3) = CheckResponse($text1,$text2,$text3,$output,"application/x-javascript",$web);
	$web_output = $web_output.$web_message1.$web_message2.$web_message3."<hr>"; 
	$commandline_output = $commandline_output.$cl_message1.$cl_message2.$cl_message3."\n"; 


// Figure out if the tests were successful.
// Are the responses all valid?
if ($status1 == "pass" && $status2 == "pass" && $status3 == "pass" && $status4 == "pass") {
	$web_response_status = $web_response_status."<font face=\"Tahoma\" size=\"3\" COLOR=\"GREEN\"><b>SUCCESS: All Content-Type header responses are valid</b></font><br><br>"; 
	$commandline_response_status = $commandline_response_status."SUCCESS: All Content-Type header responses are valid\n\n"; 
	$status = "pass";
}
else {
	$web_response_status = $web_response_status."<font face=\"Tahoma\" size=\"3\" COLOR=\"RED\"><b>FAILURE: Some Content-Type header responses are not valid</b></font><br>"; 
	$commandline_response_status = $commandline_response_status."     FAILURE: Some Content-Type header responses are not valid\n"; 
	$status = "fail";
}

$to_file = $commandline_response_status.$commandline_output;

if (isset($web)) { 
	echo $web_response_status.$web_output; }
else {
	echo $to_file; }

$filestatus = WriteResultsFile($status,$testshortname,$testname,$testdesc,$testurl,$testtime,$web,$to_file);


if (isset($debug)) { phpinfo(); }

//================= Functions =================
	
function WriteResultsFile($status,$testshortname,$testname,$testdesc,$testurl,$testtime,$web,$to_file){
//	$debug = 1;
	// Setup the archival file name for the test
	$datestamp = date("YmdGis");
	$directory = "/http/matchtest/archived_results/mimetypetest/";
	if(!is_dir($directory)){
		if(!mkdir($directory, 0777)) {
			die('Failed to create directory: '.$directory);
		}
	}

	// Write out the information to the testresults.txt file.
	$lines = file('/http/matchtest/testresults.txt');
	$numitems = count($lines);

	// Loop through our array, show HTML source as HTML source; and line numbers too.

	if (isset($debug)) { echo "<br><pre>HTTP Response Output:<br><br>"; print_r($lines); echo "</pre><br>"; }

	$newfile = $lines[0];
	$i=1;
	while($i <= $numitems) {
		$pieces = explode("|",$lines[$i]);
		if($testname == $pieces[1]){
			$replaced_line = $status."|".$testname."|".$testdesc."|".$testurl."|".$testtime."\n";
			$newfile = $newfile.$replaced_line;
		}
		else{
			$newfile = $newfile.$lines[$i];
		}
		$i++;
	}

	if (isset($debug)) { echo "<br><pre>New File Output:<br><br>"; print_r($newfile); echo "</pre><br>"; }

	$fp = fopen('/http/matchtest/testresults.txt', 'w');

	fwrite($fp, $newfile);
	fclose($fp);

// Write out results of the test to a file 
	if (isset($debug)) { echo "Filename: ".$directory.$testshortname.".web.".$status.".".$datestamp.".".$testtime.".txt<br>"; }

	if (isset($web)) { $testfilename = $directory.$testshortname.".web.".$status.".".$datestamp.".".$testtime.".txt"; }
	else { $testfilename = $directory.$testshortname.".commandline.".$status.".".$datestamp.".".$testtime.".txt"; }

	if (!$fp1 = fopen($testfilename,'w')) {
		echo "Cannot open file ($testfilename)";
		exit;
	}

	fwrite ($fp1,$to_file."\n\n");
	fclose($fp1);

	return 0;
}

function MakeAdCall($url) {
	$UserAgent="Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.2.16) Gecko/20110319 Firefox/3.6.16";

    // initilize the curl call
    $ch = curl_init();
    // set useragent
    curl_setopt($ch, CURLOPT_USERAGENT, $UserAgent);
    // Set curl to use $url for http call
    curl_setopt($ch, CURLOPT_URL, $url);
    // show client headers
    curl_setopt($ch, CURLOPT_HEADER, 1);
    // have curl put X-Forwarded-For into headers
    curl_setopt($ch,CURLOPT_HTTPHEADER, $client_headers);
    // store results as the return of curl_exec
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
    // Follow redirects
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE);		
    // if HTML error 400 over over, fail
    curl_setopt($ch, CURLOPT_FAILONERROR, TRUE);

    $output = curl_exec($ch);
    if (isset($debug)) { echo "<br><pre>HTTP Response Output:<br><br>"; print_r($output); echo "</pre><br>"; }
    //close curl connection
    curl_close($ch);

return $output;
}


function MakeOutputArray($output){
        $output_array = preg_split('/[\n]/', $output, -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);
        if (isset($debug)) { echo "<br><pre>HTTP Response Output (array):<br><br>"; print_r($output_array); echo "</pre><br>"; }

return $output_array;
}


function TraceInfo($output,$string,$debug) {

        $line_match = array_values(preg_grep("/$string/", $output));
            if (isset($GLOBALS["debug"])) { echo "DEBUG - string:  ".$string."<br>";}
            if (isset($GLOBALS["debug"])) { echo "DEBUG - output:  <br><pre>"; print_r($output); echo "</pre><br>";}
            if (isset($GLOBALS["debug"])) { echo "DEBUG - line_match:<br><pre>"; print_r($line_match); echo "</pre><br>";}
        if(stripos($line_match[0], " = ")){
			$explode = explode(" = ", $line_match[0]); }
        if(stripos($line_match[0], ":")){
			$explode = explode(":", $line_match[0]); }
        if(stripos($line_match[1], ">>>>")){
			$result = $line_match[1]; }
        if (isset($GLOBALS["debug"])) { echo "DEBUG - result:  ".$result."<br>";}
		return $result;
}

function GetFormattedOutput($output_array, $web,$debug){
        $http_response = array_values(preg_grep("/^HTTP/", $output_array));
        $http_array = explode(" ",$http_response[0]);
        $http_return_code = trim($http_array[1]);
        $http_return_text = trim($http_array[2]);
//        if (isset($debug)) { echo "<br>DEBUG - HTTP CODE/TEXT: $http_return_code / $http_return_text<br>"; }

        /* check code = 200 or 302 and text equal OK, anything else we have an error */

        if (($http_return_text != "OK" || $http_return_code != "200")&&($http_return_text != "Relocate" || $http_return_code != "302")) {
//            if (isset($debug)) { echo "***** ALERT - HTTP CODE/TEXT: ".trim($http_response[0])." *****<br>"; }
				echo "HTTP return code/text was not 200/OK". trim($http_response[0])."<br>";
                die;
        }
		
		// count the number of elements in the response array
		$num_elements = count($output_array);
//        if (isset($debug)) { echo "The Number Of Elements in the OUTPUT Array are: ".$num_elements." <br>"; }
		
		// format the items in the array as a long concatenated string.
		$y=0;
		while($y <= $num_elements){
			$formatted_output = $formatted_output.$output_array[$y]."\n";
			$formatted_output_web = $formatted_output_web.$output_array[$y]."<br>";
			$y++;
		}
//        if (isset($debug)) { echo "The Formatted contents of OUTPUT are: ".$formatted_output_web." *****<br>"; }
		
		if($web) {
			return $formatted_output_web; }
		else {
			return $formatted_output; }
}

function CheckResponse($text1,$text2,$text3,$output,$SearchString,$web){

		$response = print_r($output,TRUE);
		if(stripos($output, $SearchString)){
			$message1 = "***** SUCCESS - ".$text1;
			$message2 = $text2;
			$message3 = $text3;
			$web_message1 = $message1."<br>";
			$cl_message1 = $message1."\n"; 
            $web_message2 = $message2."";
			$cl_message2 = $message2."\n"; 
			$web_message3 = "<pre>".$message3."<br><br><textarea readonly name=\"text\" style=\"width: 1300px; height: 300px\">".$response."</textarea></pre><br>"; 
			$cl_message3 = "".$message3."\n".$response."\n"; 
			$status = "pass";
        }
        else {
			$message1 = "***** ALERT - Targeting doesn't match. Targeting IS NOT WORKING: $TraceTargeting";
			$message2 = "***** Writing out failure to testresults.txt";
			$message3 = "HTTP Response Output:";
            $web_message1 = $message1."<br>"; 
            $cl_message1 = $message1."\n"; 
            $web_message2 = $message2."";
            $cl_message2 = $message2."\n";
			$web_message3 = "<br><pre>".$message3."<br><br>".$response."</pre><br>"; 
			$cl_message3 = "\n".$message3."\n".$response."\n"; 
			$status = "fail";			
		}
	return array($status,$web_message1,$web_message2,$web_message3,$cl_message1,$cl_message2,$cl_message3);
}


?>
